//
//  MBDModifyUserWeChatViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/10/25.
//

import Foundation


import UIKit
import YYText
import SnapKit

import Toast_Swift
import MJRefresh


class MBDModifyUserWeChatViewController : MBDBaseViewController {
    
    var tableView: UITableView!
    var saveInfoBlock: KButtonBlock!
    var viewModel : MBDModifyUserWeChatViewModel!
    var authButton : UIButton!
    
    init(viewModel : MBDModifyUserWeChatViewModel) {
        super.init(nibName: nil, bundle: nil)
        self.viewModel = viewModel
    }
    
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = self.viewModel.title
        
        let rightItem = UIButton(frame: CGRectMake(0, 0, 44, 44))
        rightItem.setTitle("保存", for: .normal)
        rightItem.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        rightItem.addTarget(self, action: #selector(rightItemPressed), for: .touchUpInside)
        rightItem.setTitleColor(UIColor(colorHex: 0x4273d0), for: .normal)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItem)
        
        tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(tableView)
        
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.view)
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            make.height.equalTo(self.view)
        }
        
        tableView.backgroundColor = UIColor(colorHex: 0xF4F4F4)
        tableView.contentInset = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0)
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        
        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 100

        tableView.register(MBDTextEditCell.self, forCellReuseIdentifier: "MBDTextEditCell")
        
        //验证
        authButton = UIButton()
        authButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        authButton.addTarget(self, action: #selector(authPressed), for: .touchUpInside)
        
        let current : MBDAccountInfoModel! = MBDAccountInfoModel.current()
        //判断是否已经认证过
        if (current.weChatNumberOcr == current.weChatNumber) {
            authButton.setTitle("已认证", for: .normal)
            authButton.setTitleColor(UIColor.gray, for: .normal)
            authButton.isEnabled = false
        } else {
            authButton.setTitle("去认证", for: .normal)
            authButton.setTitleColor(UIColor(colorHex: 0x4273d0), for: .normal)
            authButton.isEnabled = true
        }
        
        self.view.addSubview(authButton)
        
        self.authButton.snp.makeConstraints { make in
            make.centerX.equalTo(self.tableView)
            make.top.equalTo(180)
            make.left.equalTo(15)
            make.width.equalToSuperview()
            make.height.equalTo(44)
        }
        
        self.view.setDynamicBackgroundColor()
        tableView.setDynamicBackgroundColor()
    }
    
    override func updateColors() {
        self.view.setDynamicBackgroundColor()
        tableView.setDynamicBackgroundColor()
        self.tableView.reloadData()
    }
    
    @objc func rightItemPressed(){
        let cellModel = self.viewModel.cellModels.first as! MBDModifyInfoBaseCellModel
        let viewModel = self.viewModel!
        
        viewModel.doRequest(info: cellModel.text!) { error,result in
            if nil != error {
                self.view.makeToast(error?.localizedDescription)
            } else {
                MBDAccountInfoModel.current()?.update(notify: true)
                
                self.navigationController?.popViewController(animated: true)
            }
            
        }
    }
    
    @objc func authPressed(){
//        let apvc = MBDAvatarPickerViewController()
//        self.navigationController?.pushViewController(apvc, animated: true)
        
        let picker = UIImagePickerController()
        picker.sourceType = .photoLibrary
        picker.allowsEditing = false
        picker.delegate = self
        present(picker, animated: true)
        
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
    
    override var prefersStatusBarHidden: Bool {
        return false
    }
    
}


extension MBDModifyUserWeChatViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellModel = self.viewModel.cellModels[indexPath.row] as! MBDCommonCellModel
        return cellModel.cellHeight()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let cellModel = self.viewModel.cellModels[indexPath.row] as! MBDModifyInfoBaseCellModel
        if let realBlock = cellModel.cellWillDisplayBlock {
            realBlock()
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
    }
}


extension MBDModifyUserWeChatViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.cellModels.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cellModel = self.viewModel.cellModels[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "MBDTextEditCell", for: indexPath)
        (cell as! MBDCommonCell).cellModel = cellModel
        return cell
    }
}


extension MBDModifyUserWeChatViewController :UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else{
            return
        }
        
//        self.avatarImageView.image = image
                
        let imageData = image.compressImage()
        
        self.startIndicatorAnimating()

        //先上传图片，再更新用户信息
        self.uploadPic(imageData: imageData) { error, picPath in
            //上传后判断结果
            if nil == error {
                //更新信息后判断结果
//                self.updateUserInfo(picPath: picPath!) { er, result in
//                    self.stopIndicatorAnimationg()
//
//                    if nil == er {
//                        self.view.makeToast("上传成功！")
//                        
//                        MBDAccountInfoModel.current()?.update(notify: true)
//                    } else {
//                        self.view.makeToast(er!.localizedDescription)
//                    }
//                    
//                }
                
            } else {
                self.stopIndicatorAnimationg()
                self.view.makeToast(error?.localizedDescription)

            }
        }

    }
    
    func uploadPic(imageData : Data,completionHandler: @escaping (NSError?,String?) -> Void) {
        MBDHttpClient.shared.doUploadFileRequest("/ocr/personalCenter", data: imageData, fileName: "file").httpClientResponse { error, response in
            
            if nil == error {
                let rawDict = response?.rawDict
                let data : String = rawDict?["data"] as! String

                //返回值
                if data.isBlank {
                    completionHandler(error,nil)
                } else {
                    completionHandler(nil,data)
                }
                
            } else {
                //返回值
                completionHandler(error,nil)
            }
        }
    }
    
//    func updateUserInfo(picPath : String,completionHandler: @escaping (NSError?, Bool?) -> Void){
//        
//        if let current = MBDAccountInfoModel.current() {
//            var params : Dictionary<String, Any>
//            params = ["userId":String(current.userId),"avatarUrl":String(picPath)]
//
//            MBDHttpClient.shared.request("/user/update",method: .put,parameters: params,encoding: JSONEncoding.default).httpClientResponse { error, response in
//                
//                if nil != error {
//                    completionHandler(error,false)
//                } else {
//                    completionHandler(nil,true)
//                }
//            }
//        } else {
//            let error : NSError = NSError(domain: "do not login", code: 10000)
//            completionHandler(error,false)
//        }
//    }
    
}
